<?php

namespace app\admin\controller;

use app\admin\library\Auth;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\db\exception\BindParamException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 初装费收入
 *
 * @icon fa fa-circle-o
 */
class Ydchuzhuang extends Backend
{

    /**
     * Ydchuzhuang模型对象
     * @var \app\admin\model\Ydchuzhuang
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Ydchuzhuang;
        $this->view->assign("ptypeList", $this->model->getPtypeList());
        $this->view->assign("isJidingList", $this->model->getIsJidingList());
        $this->view->assign("isQuanwuList", $this->model->getIsQuanwuList());
        $this->view->assign("isQuanguangList", $this->model->getIsQuanguangList());
        $this->view->assign("isKanjiaList", $this->model->getIsKanjiaList());
        $this->view->assign("gtypeList", $this->model->getGtypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if(isLimit()){
                $limit = 99999;
            };
            $list = $this->model
                    //->with(['lanzhuang','shouli'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            $sum_arr = [];
            $sum_arr2 = [];
            $sum_arr3 = [];
            $sum_arr4 = [];
            $sum_arr5 = [];
            $sum_arr6 = [];
            $sum_arr7 = [];
            foreach ($list as $row) {
                $sum_arr[] = $row->price;
                $sum_arr2[] = $row->lan_fee;
                $sum_arr3[] = $row->shouli_fee;
                $sum_arr4[] = $row->an_fee;
                $sum_arr5[] = $row->jd_money;
                $sum_arr6[] = $row->qw_money;
                $sum_arr7[] = $row->qg_money;
                $row->visible(['id','opt_date','name','mobile','address','price','lan_fee','ptype','zhuang_date','shouli_fee','an_fee','is_jiding','jd_money','is_quanwu','qw_money','is_quanguang','qg_money','is_kanjia','lanzhuang_id','an_id','shouli_id','gtype','remark','createtime','updatetime']);
              /*  $row->visible(['lanzhuang']);
				$row->getRelation('lanzhuang')->visible(['name']);
				$row->visible(['shouli']);
				$row->getRelation('shouli')->visible(['name']);*/
                //$c = $this->model->where('opt_date',$row->opt_date)->count();
                //if($c > 1 ){
                   /*  $sum = $this->model->where('opt_date',$row->opt_date)->sum('price');
                    $row->price = $row->price.PHP_EOL.'日合计:'.float_two($sum);
                    $sum2 = $this->model->where('opt_date',$row->opt_date)->sum('lan_fee');
                    $row->lan_fee = $row->lan_fee.PHP_EOL.'日合计:'.float_two($sum2);
                    $sum3 = $this->model->where('opt_date',$row->opt_date)->sum('shouli_fee');
                    $row->shouli_fee = $row->shouli_fee.PHP_EOL.'日合计:'.float_two($sum3);
                    $sum4 = $this->model->where('opt_date',$row->opt_date)->sum('an_fee');
                    $row->an_fee = $row->an_fee.PHP_EOL.'日合计:'.float_two($sum4);
                    $sum5 = $this->model->where('opt_date',$row->opt_date)->sum('jd_money');
                    $row->jd_money = $row->jd_money.PHP_EOL.'日合计:'.float_two($sum5);
                    $sum6 = $this->model->where('opt_date',$row->opt_date)->sum('qw_money');
                    $row->qw_money = $row->qw_money.PHP_EOL.'日合计:'.float_two($sum6);
                    $sum7 = $this->model->where('opt_date',$row->opt_date)->sum('qg_money');
                    $row->qg_money = $row->qg_money.PHP_EOL.'日合计:'.float_two($sum7);*/
                //}
            }

            $rows = $list->items();
            if(!empty($rows)){
                $firstarr[]=[
                    'price'          => '总计: '.float_two(array_sum($sum_arr)),
                    'lan_fee'          => '总计: '.float_two(array_sum($sum_arr2)),
                    'shouli_fee'          => '总计: '.float_two(array_sum($sum_arr3)),
                    'an_fee'          => '总计: '.float_two(array_sum($sum_arr4)),
                    'jd_money'          => '总计: '.float_two(array_sum($sum_arr5)),
                    'qw_money'          => '总计: '.float_two(array_sum($sum_arr6)),
                    'qg_money'          => '总计: '.float_two(array_sum($sum_arr7)),
                ];
                $rows = array_merge($rows, $firstarr);
            }
            $price_sum = $this->model->where($where)->sum('price');
            $lan_sum = $this->model->where($where)->sum('lan_fee');
            $shouli_sum = $this->model->where($where)->sum('shouli_fee');
            $an_sum = $this->model->where($where)->sum('an_fee');
            $jd_sum = $this->model->where($where)->sum('jd_money');
            $qw_sum = $this->model->where($where)->sum('qw_money');
            $qg_sum = $this->model->where($where)->sum('qg_money');

            $result = array("total" => $list->total(), "rows" => $rows
            ,"extend" => ['money' => $price_sum,'lan_sum'=>$lan_sum,
                    'shouli_sum'=>$shouli_sum,'an_sum'=>$an_sum,
                    'jd_sum'=>$jd_sum,'qw_sum'=>$qw_sum,
                    'qg_sum'=>$qg_sum]);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        if(ydlock_data($params['opt_date'])){
            $this->error('财务已锁定本月数据，无法操作');
        }
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            ydday_in($params['opt_date'],$params['price'],$this->model->getGtypeV($params['gtype']),$params['ptype'],$params['name']);
            create_dxuser($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        if(ydlock_data($params['opt_date'])){
            $this->error('财务已锁定本月数据，无法操作');
        }
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            ydday_in($params['opt_date'],$params['price'],$this->model->getGtypeV($params['gtype']),$params['ptype'],$params['name']);
            create_dxuser($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'xls') {
            $reader = new Xls();
            $reader->setReadDataOnly(true);
        } else {
            $reader = new Xlsx();
            $reader->setReadDataOnly(true);
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);

                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        if(empty($row[$fieldArr[$k]]) && isset($row['name'])){
                            //break;
                        }
                        $row[$fieldArr[$k]] = $v;
                        //echo $fieldArr[$k].'<br/>';

                    }
                }

                if ($row) {
                    $insert[] = $row;
                }
            }
            //print_r($insert);
            //die();
            $insert2 = [];
            foreach ($insert as $k1 => $v1) {
                //print_r($v1);die();
                if(!empty($v1['mobile']) && !empty($v1['opt_date'])){
                    $v1['opt_date'] = excelDateToPhp($v1['opt_date']);
                    $v1['zhuang_date'] = excelDateToPhp($v1['zhuang_date']);
                    $zhichu = array_search($v1['ptype'],  $this->model->getPtypeList());
                    $v1['ptype'] = $zhichu?:0;
                    $zhichu2 = array_search($v1['gtype'],  $this->model->getGtypeList());
                    $v1['gtype'] = $zhichu2?:0;
                    $v1['is_jiding'] = $v1['is_jiding']=='是'?1:0;
                    $v1['is_quanwu'] = $v1['is_quanwu']=='是'?1:0;
                    $v1['is_quanguang'] = $v1['is_quanguang']=='是'?1:0;
                    $v1['is_kanjia'] = $v1['is_kanjia']=='是'?1:0;
                    /* $type = array_search($v1['ztype'],  $this->model->getZtypeList());
                     $v1['ztype'] = $type?:0;*/
                    //  print_r($v1);
                    $insert2[$k1] = $v1;
                    //print_r($insert2);
                }else{
                    break;
                }
            }
            $insert = $insert2;
            //die();
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

}
